document.addEventListener("DOMContentLoaded", () => {
    const forms = document.querySelectorAll("form");

    forms.forEach(form => {
        form.addEventListener("submit", (event) => {
            let isValid = true;

            // 检查所有必填字段
            const requiredFields = form.querySelectorAll("[required]");
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add("error");
                    const errorMessage = document.createElement("span");
                    errorMessage.className = "error-message";
                    errorMessage.innerText = `${field.name} is required.`;
                    if (!field.nextElementSibling || !field.nextElementSibling.classList.contains("error-message")) {
                        field.parentElement.appendChild(errorMessage);
                    }
                } else {
                    field.classList.remove("error");
                    if (field.nextElementSibling && field.nextElementSibling.classList.contains("error-message")) {
                        field.parentElement.removeChild(field.nextElementSibling);
                    }
                }
            });

            if (!isValid) {
                event.preventDefault(); // 阻止提交
            }
        });
    });
});
